<template>
  <el-card class="box-card">
    <template v-slot:header>
        <div class="clearfix">
         <span>更换头像</span>
        </div>
    </template>

    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img :src="avatar" alt="" v-if="avatar"/>
      <img src="../../../assets/images/avatar.jpg" alt="" v-else/>

      <!-- 按钮区域 -->
      <div class="btn-box">
          <input type="file" accept="image/*" style="display:none;" ref="iptRef" @change="onIptChange">
        <el-button type="primary" icon="el-icon-plus" @click="chooseImg">选择图片</el-button>
        <el-button type="success" icon="el-icon-upload" :disabled="avatar === ''" @click="uploadImg">上传头像</el-button>
      </div>
    </div>
  </el-card>
</template>

<script>
export default {
  name: 'UserAvatar',
  data () {
    return {
      avatar: ''
    }
  },
  methods: {
    chooseImg () {
      this.$refs.iptRef.click()
    },
    onIptChange (e) {
    //   console.dir(e.target)
      if (e.target.files.length === 0) {
        // 没有选择图片
      } else {
        // e.target.files[0]
        const reader = new FileReader()
        reader.readAsDataURL(e.target.files[0])
        reader.onload = () => {
        //   console.log(reader.result)
          this.avatar = reader.result
        }
      }
    },
    async uploadImg () {
      const { data: res } = await this.$http.patch('/my/update/avatar', { avatar: this.avatar })
      if (res.code === 0) {
        this.$store.dispatch('initUserInfo')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
}
</style>
